<?php
/**
 * setup the framework
 * @author: Mark Gil M. Libres
 * @email: markglibres@yahoo.com,
 * @on: 1/21/2008
 */
require_once("define.php");

/**
 * include classes used by setupZend()
 * @author: markg
 * @on: 1/23/2008
 */
 //start
require_once(ZEND_DIR."Controller/Front.php");
Zend_Loader::loadClass("Zend_Controller_Router_Route");
Zend_Loader::loadClass("Zend_Controller_Router_Rewrite");
//Zend_Loader::loadclass('Front');
//end
/**
 * include classes used by setupSmarty()
 * @author: markg
 * @on: 1/23/2008
 */
 //start
Zend_Loader::loadClass("Zend_Config_Ini");
Zend_Loader::loadClass("Zend_Registry");
Zend_Loader::loadClass("Zend_Session_Namespace");

require_once(SMARTY_DIR."Smarty.class.php");
//end

/**
 * include classes used by initialize()
 * @author: markg
 * @on: 1/29/2008
 */
 Zend_Loader::loadClass("Zend_Log");
 Zend_Loader::loadClass("Zend_Log_Writer_Stream");
 
 /**
  * include classes used by Model()
  * @author: markg
  * @on: 1/30/2008
  */
  Zend_Loader::loadClass("Datasource");
  Zend_Loader::loadClass("Zend_Db_Table_Abstract");


 
class DWCSetup
{
	/**
	 * initialize framework setup
	 * @author: markg
	 */
	function initialize($client_dir = "")
	{
		/**
		* support for "subfolder" url, not subdomain clients
		* @author: markg
		* @on: 1/11/2009
		*/
		DWCSetup::setClient($client_dir);
		
		
		/**
		 * loads the config file used by the DWC framework, not the config specific for an application
		 * @author: markg
		 */
		$dwc_config = new Zend_Config_Ini(CAD_DIR."config.ini");
		Zend_Registry::set(REGISTRY_DWC, $dwc_config);
		
		
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		
		
		
		/**
		 * initialize logger system
		 * @author: markg
		 */
		 $logger = new Zend_Log();
		 //$stream = @fopen(ROOT_DIR.$dwc_config->dwc->logs."/".date("M-d-y").".txt", 'a+');
		 $format = '%timestamp% Priority (%priority%): %message%' . PHP_EOL;
		 $formatter = new Zend_Log_Formatter_Simple($format);
		 /**
		  * TODO: define client specific logging
		  * @author: markg
		  */
		 $client_config = new Zend_Config_Ini($client_session->CLIENT_DIR."config.ini");
		 $logFile = $client_session->CLIENT_DIR.$client_config->paths->log."/".date("Ymd").".txt";
		 $writer = new Zend_Log_Writer_Stream($logFile,"a+");
		 $writer->setFormatter($formatter);
		 $logger->addWriter($writer);
		 
		 ini_set("log_errors" , "1");
		 ini_set("error_log" , $logFile);
		 ini_set("display_errors" , "0");
		 
		 //this should allow for session to last up to 120 mins
		 $garbage_timeout = 7200; // 3600 seconds = 60 minutes = 1 hour // 7200 = 120 mins
		 ini_set('session.gc_maxlifetime', $garbage_timeout);
		 $sessdir = $client_session->CLIENT_DIR."tmp/";
		 ini_set("session.save_path", $sessdir);
		 
		 $client_session->config = $client_config;
		 $client_session->logger = $logger;
		 DWCSetup::secureSite();
 		 //Zend_Registry::set(REGISTRY_LOG, $logger);
 		 
 		  /**
		  * load the default controller for the entire application
		  * @author: markg
		  * @on: 3/3/2008
		  */	
		 Zend_Loader::loadClass("BaseController");
		 
		 /**
		  * sets the default login expiry
		  * @author: markg
		  * @on: 5/30/2008
		  */
		 Zend_Loader::loadClass("BaseAuth");
		 
		 if($client_config->auth)
		 {
		 	if($client_config->auth->expiry)
		 		BaseAuth::setExpiryMinutes($client_config->auth->expiry);
		 }
		 elseif($dwc_config->auth)
		 {
		 	 if($dwc_config->auth->expiry)
		 		 BaseAuth::setExpiryMinutes($dwc_config->auth->expiry);
		 }
		 
		 /**
	     * TODO: this should be automated and not hardcoded
	     * add modules/models and modules/models/tables to path
	     * @author: markg
	     */
	     ini_set("include_path", ini_get("include_path") . PATH_SEPARATOR .
			DEFAULT_DIR . "models/".PATH_SEPARATOR .
			DEFAULT_DIR . "classes/".PATH_SEPARATOR .
			APP_DIR."module1/models/" . PATH_SEPARATOR .
			APP_DIR."module1/classes/" . PATH_SEPARATOR);
	}
	
	
	function Controller()
	{
		
		/**
		 * rewrite route to support modules
		 * @author: markg
		 */
		
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);    
		if($client_session->subURLClient)
		{
			$router = new Zend_Controller_Router_Rewrite();
			$route = new Zend_Controller_Router_Route(
		    ':clientname/:module/:controller/:action/*',
		    array('module' => 'default'));
		}
		else
		{
			$router = new Zend_Controller_Router_Rewrite();
			$route = new Zend_Controller_Router_Route(
		    ':module/:controller/:action/*',
		    array('module' => 'default'));
		}
		
		$router->addRoute('default', $route);

	    /**
	     * TODO: try to set modules thru ini file
	     * and add to path for the models
	     * and libs
	     * @author: markg
	     */
	    //$module_config = new Zend_Config_Ini(DOC_ROOT."modules.ini","modules");
	    //$router->addConfig($module_config,'routes');
		
		/**
		 * set default controller directory
		 * @author: markg
		 */
		$front = Zend_Controller_Front::getInstance();
		$front->setControllerDirectory(array(
	    'default' => APP_CONTROLLERS));
	    
	    
	    /**
	     * TODO: this should be automated and not hardcoded
	     * * add module directory
	     * @author: markg
	     */
	  //   $front->addControllerDirectory(APP_DIR."module1/controllers","module1");
		
		Zend_Controller_Front::getInstance()->setParam('noErrorHandler', true)->throwExceptions(true);
	    $front->setParam('noViewRenderer', true);
	    //$front->setParam('noErrorHandler', true);
	    $front->dispatch();
	    
	   
	}
	
	function View()
	{
		
		$smarty_config = Zend_Registry::get(REGISTRY_DWC)->smarty;
		$smarty = new Smarty();
		$smarty->debugging = $smarty_config->debugging;
		$smarty->force_compile = $smarty_config->force_compile;
		$smarty->caching = $smarty_config->caching;
		$smarty->compile_check = $smarty_config->compile_check;
		$smarty->cache_lifetime = $smarty_config->cache_lifetime;
		$smarty->cache_dir = ROOT_DIR.$smarty_config->cache_dir;
		$smarty->compile_dir = ROOT_DIR.$smarty_config->cache_compile_dir;
		$smarty->plugins_dir = array(
		  SMARTY_DIR . 'plugins',
		  'resources/plugins');
		Zend_Registry::set(REGISTRY_VIEW, $smarty);
	
	}
	
	/**
	 * setup the model (Zend_DB)
	 * @author: markg
	 * @on: 1/30/2008
	 */
	 function Model()
	{
	 	/**
	 	 * make db connection available globally
	 	 */
	 	Zend_Loader::loadClass("DBCon");
	 	/**
	 	 * added try catch for static sites
	 	 * @author: markg
	 	 * @on: 8/5/2008
	 	 */
	 	try{
	 		/**
		 	 * set the default Adapter when extending Zend DB Table Class
		 	 * @author: markg
		 	 * @on: 2/22/2008
		 	 */
		 	$datasource = DBCon::instance();
		 	
		 	$zend_config = Zend_Registry::get(REGISTRY_DWC)->zend;
		 	if($zend_config && $zend_config->enable_cache)
		 	{
		 		
			 	/**
			 	 * caching of metadata
			 	 */
			 	$frontendOptions = array(
				    'automatic_serialization' => true
				    );
				
				$backendOptions  = array(
				    'cache_dir'                => ROOT_DIR.$zend_config->metadata_cache_dir
				    );
				
				Zend_Loader::loadClass("Zend_Cache");
				$cache = Zend_Cache::factory('Core',
				                             'File',
				                             $frontendOptions,
				                             $backendOptions);
				Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
				       
		 	}
		 	Zend_Db_Table_Abstract::setDefaultAdapter($datasource->getConnection());
	 	}
	 	catch (Exception $e)
	 	{
	 		
	 	}
	 	
	 	
	}
	
	function setClient($client_dir = "")
	{
		
		Zend_Loader::loadClass("Zend_Session_Namespace");
		$client_session = new Zend_Session_Namespace(SESSION_CLIENT);
		
		/**
		 * loads the config file used by the application
		 * @author: markg
		 */
		$app_config = new Zend_Config_Ini(DOC_ROOT."config.ini");
		
		
		 /**
		 * add optional $client_dir param.. this can be used when running from cron jobs
		 * @author: karl
		 * @on: 2/4/2009
		 */
		if(!$client_dir){
			/**
			* support for "subfolder" url, not subdomain clients
			* @author: markg
			* @on: 1/11/2009
			*/
			$subURLClient = false;
			if(isset($app_config->app->clientOnSubURLSecureSiteOnly) && $app_config->app->clientOnSubURLSecureSiteOnly)
			{
				if(isset($_SERVER['HTTPS']) || isset($_SERVER['HTTP_X_FORWARDED_SERVER']))
					$subURLClient = true;	
				
			}
			if(isset($app_config->app->clientOnSubURL) && $app_config->app->clientOnSubURL && !$app_config->app->clientOnSubURLSecureSiteOnly)
			{
				$subURLClient = true;
			}
			
			if($subURLClient)
			{
				$uri = $_SERVER["REQUEST_URI"];
				$uri = explode("/",$uri);
				$client_dir = $uri[1];
				
				/**
				 * logout automatically if switch of clients
				 * @author: markg
				 * @on: 1/11/2009
				 */
				 if($client_session->loggedClient != $client_dir)
				 {
				 	$client_session->app_logout = true;
				 	$client_session->loggedClient = $client_dir;
				 }
				 $client_session->subURLClient = true;
			}
			else
			{
				$url = $_SERVER['SERVER_NAME'];
				$url = explode(".",$url);
				$config_dir = "";
				if(count($url) >= 3 && substr($url[0],0,3) != "www")
				{
					$client_dir = $url[0];
				}
				else
				{
					$client_dir = "default";
				}
			}
		}

		$client_session->CLIENT_DIR = ROOT_DIR."clients/".$client_dir."/";
		$client_session->CLIENT_EXT = $client_dir;
		$client_session->CLIENT_WWW = "/cad_clients/".$client_dir."/";
		//define("CLIENT_DIR",ROOT_DIR."clients/".$client_dir."/");
		//define("CLIENT_EXT",$client_dir);
		//define("CLIENT_WWW","/cad_clients/".$client_dir."/");
		
	}	
	
	/**
	 * redirects user to the secure site if forced
	 * @author: markg
	 * @on: 04/01/2009
	 */
	function secureSite()
	{
		/**
  		 * loads the config file specific for the client
  		 * @author: markg
  		 * @on: 4/01/2009
  		 */  
  		$client_session = new Zend_Session_Namespace(SESSION_CLIENT); 		
  		$client_config = $client_session->config;
  		if (!empty($client_config->https->force) && $client_config->https->force){  			  		  		
	  		
	  		if(!(isset($_SERVER['HTTPS']) || isset($_SERVER['HTTP_X_FORWARDED_SERVER'])))
	  		{
	  			$httpsURL = "https://".$_SERVER['HTTP_HOST'];
		  		if(!empty($client_config->https->url))
		  		{
		  			$httpsURL = ereg_replace("(\/)*$","",$client_config->https->url);
		  			$httpsURL = $httpsURL.$_SERVER["REQUEST_URI"];
		  		}
	  			header("Location: ".$httpsURL);
	  			exit();
	  		}
  		}
	}
	 
}
?>